package gk.example.activity;

import gk.example.BaseActivity;
import gk.example.bean.User;
import gk.example.util.ErrorCodeUtil;
import gk.example.util.T;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.AsyncCustomEndpoints;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.CloudCodeListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.ResetPasswordListener;

import com.example.gkdate.R;

/**
 * 
 * Description:重置密码界面
 * 
 * @author Wenk.Chan（最新修改者）
 * @version 1.0（最新版本号）
 */
public class ResetPasswordActivity extends BaseActivity implements
		OnClickListener {
	private Button mBtnResetPassWord;
	private ImageButton mBtnBack;
	private EditText mEtReset;
	private TextView mTvTitle;
	private int mResetForm;
	private String mContact;
	private CompoundButton mCbShowPassWord;

	@Override
	protected void initView() {
		setContentView(R.layout.activity_reset_password);
		mBtnResetPassWord = (Button) findViewById(R.id.btn_reset_password);
		mCbShowPassWord = (CompoundButton) findViewById(R.id.cb_reset_show_password);
		mEtReset = (EditText) findViewById(R.id.et_reset);
		mTvTitle = (TextView) findViewById(R.id.tv_top_title);
		mBtnBack = (ImageButton) findViewById(R.id.btn_back);

	}

	@Override
	protected void initEvent() {
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		mResetForm = bundle.getInt("reset");
		mContact = bundle.getString("phone");
		mTvTitle.setText(getResources().getString(R.string.reset_password));
		if (mResetForm == 0x11) {
			mTvTitle.setText("利用手机号码重置密码");
			mEtReset.setHint("请输入密码");

		} else if (mResetForm == 0x12) {
			mTvTitle.setText("利用邮箱地址重置密码");
			mEtReset.setHint("请输入邮箱地址");
			mCbShowPassWord.setVisibility(View.GONE);
		}

		mBtnBack.setOnClickListener(this);
		mBtnResetPassWord.setOnClickListener(this);
		mCbShowPassWord
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) {
							mEtReset.setInputType(InputType.TYPE_CLASS_TEXT
									| InputType.TYPE_TEXT_VARIATION_NORMAL);

						} else {
							mEtReset.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD
									| InputType.TYPE_CLASS_TEXT);

						}

					}
				});
	}

	/**
	 * 
	 * 描述：利用手机号找回密码
	 * 
	 * @return void
	 */
	private void resetPasswordByPhone() {
		final String password = mEtReset.getText().toString();
		if (password.length() < 6) {
			T.show(this, "密码不能少于六位", Toast.LENGTH_SHORT);
			return;
		} else if (password.matches("^[\u4E00-\u9FA5]+$")) {
			T.show(this, "密码不能含有中文", Toast.LENGTH_SHORT);
			return;
		}
		BmobQuery<User> query = new BmobQuery<User>();
		query.addWhereEqualTo("Contact", mContact);
		query.findObjects(this, new FindListener<User>() {

			@Override
			public void onSuccess(List<User> arg0) {
				if (arg0.size() > 0) {
					resetPassword(arg0.get(0).getUsername(), password);
				}

			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(ResetPasswordActivity.this, arg0, arg1);
			}
		});
	}

	/**
	 * 
	 * 描述： 云端重置密码
	 * 
	 * @return void
	 */
	private void resetPassword(String username, String password) {
		AsyncCustomEndpoints ace = new AsyncCustomEndpoints();
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("phone", username);
			jsonObject.put("password", password);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// 第一个参数是上下文对象，第二个参数是云端代码的方法名称，第三个参数是上传到云端代码的参数列表（JSONObject
		// cloudCodeParams），第四个参数是回调类
		ace.callEndpoint(this, "PhoneReset", jsonObject,
				new CloudCodeListener() {

					@Override
					public void onSuccess(Object arg0) {
						// TODO Auto-generated method stub
						T.show(ResetPasswordActivity.this, "密码重置成功",
								Toast.LENGTH_SHORT);
						finish();
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						ErrorCodeUtil.Errorshow(ResetPasswordActivity.this, arg0, arg1);
					}
				});
	}

	/**
	 * 
	 * 描述： 利用邮箱地址找回密码
	 * 
	 * @return void
	 */
	private void resetPasswordByEmail() {
		String resetEmail = mEtReset.getText().toString();
		BmobUser.resetPassword(this, resetEmail, new ResetPasswordListener() {

			@Override
			public void onSuccess() {
				T.show(ResetPasswordActivity.this, "重置请求已发到邮箱，请查收",
						Toast.LENGTH_SHORT);
				startActivity(new Intent(ResetPasswordActivity.this,
						LoginActivity.class));
				finish();
			}

			@Override
			public void onFailure(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(ResetPasswordActivity.this, arg0, arg1);
			}
		});

	}

	/**
	 * 
	 * 描述： 返回提示对话框
	 * 
	 * @return void
	 */
	private void showBackDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("提示");
		builder.setMessage("您还没重置,确定返回?");
		builder.setNegativeButton("确定",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						startActivity(new Intent(ResetPasswordActivity.this,
								LoginActivity.class));
						finish();
					}
				});
		builder.setPositiveButton("取消",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			showBackDialog();
			break;
		case R.id.btn_reset_password:
			if (TextUtils.isEmpty(mEtReset.getText())) {
				T.show(ResetPasswordActivity.this, "请填写邮箱地址" ,
						Toast.LENGTH_SHORT);
				break;
			}
			// 手机号
			if (mResetForm == 0x11) {
				resetPasswordByPhone();
			}
			// 邮箱
			else if (mResetForm == 0x12) {
				resetPasswordByEmail();
			}

			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showBackDialog();
		}
		return super.onKeyDown(keyCode, event);
	}
}
